import { Injectable } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import { Repository } from 'typeorm';
import { Book } from '@/modules/book/book.entity';
import path from 'path';
import fs from 'fs';
import EpubBook from '@/modules/book/epub-book';

@Injectable()
export class BookService {
  constructor(
    @InjectRepository(Book) private readonly bookRepository: Repository<Book>,
  ) {}

  // 查询电子书列表
  getBookList(query: any = { page: 1, pageSize: 20 }) {
    let page = query.page || 1;
    let pageSize = query.pageSize || 20;
    const { title = '', author = '' } = query;
    if (page <= 0) {
      page = 1;
    }
    if (pageSize <= 0) {
      pageSize = 20;
    }
    let where = 'where 1 = 1';
    if (title) {
      where += ` and title like '%${title}%'`;
    }
    if (author) {
      where += ` and author like '%${author}%'`;
    }
    const sql = `select * from book ${where} limit ${pageSize} offset ${(page - 1) * pageSize}`;
    return this.bookRepository.query(sql);
  }

  // 查询电子书总数
  countBookList(query: any) {
    const { title = '', author = '' } = query;
    let where = 'where 1 = 1';
    if (title) {
      where += ` and title like '%${title}%'`;
    }
    if (author) {
      where += ` and author like '%${author}%'`;
    }
    const sql = `select count(*) as count from book ${where}`;
    return this.bookRepository.query(sql);
  }

  // 根据id获取电子书详情
  getBookById(id: number) {
    const sql = `select * from book where ID = ${id}`;
    return this.bookRepository.query(sql);
  }

  // 上传电子书
  uploadBook(file) {
    const desDir = path.join(process.cwd(), 'src', 'upload');
    const desPath = path.resolve(desDir, file.originalname);
    fs.writeFileSync(desPath, file.buffer);
    // 解析电子书
    return this.parseBook(desPath, file).then((rootFile) => {
      console.log('rootFile1', rootFile);
      return {
        originalname: file.originalname,
        mimetype: file.mimetype,
        size: file.size,
        path: desPath,
        dir: desDir,
      };
    });
  }

  // 解析电子书
  parseBook(bookPath, file) {
    const epub = new EpubBook(bookPath, file);
    return epub.parse();
  }

  // 新增电子书
  addBook(body) {
    const {
      title,
      author,
      fileName,
      category,
      categoryText,
      cover,
      language,
      publisher,
      rootFile,
    } = body;
    const sql = `insert into book(fileName, cover, title, author, publisher, bookId, category, categoryText, language, rootFile) values ('${fileName}', '${cover}', '${title}', '${author}', '${publisher}', '${fileName}', '${category}', '${categoryText}', '${language}', '${rootFile}')`;
    return this.bookRepository.query(sql);
  }
}
